﻿using Common.Result;
using Microsoft.AspNetCore.Mvc;
using Model.Dto;
using Service;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly ILogger<UserController> _logger;
        public UserController(IUserService userService, ILogger<UserController> logger)
        {
            _logger = logger;
            _userService = userService;
        }
        [HttpGet("page")]
        public async Task<ApiResult> GetUserPageInfo(int pageNum, int pageSize, string? username)
        {
            _logger.LogInformation("请求参数为：pageNum:{},pageSize:{},username,{}",
                pageNum, pageSize, username);
            PageInfo pageInfo = await _userService.GetUserPageInfoAsync(pageNum, pageSize, username);
            return ResultHelper.Success(pageInfo);
        }
        [HttpPost]
        public async Task<ApiResult> SaveUser(UserReq userReq)
        {
            _logger.LogInformation("请求参数为：userReq:{}", userReq.ToString());
            var res = await _userService.AddUserAsync(userReq);
            if (res) { return ResultHelper.Success("添加成功"); }
            return ResultHelper.Error("添加失败");
        }
        [HttpDelete("{id}")]
        public async Task<ApiResult> DeleteUser(int id)
        {
            _logger.LogInformation("请求参数为：id:{}", id);
            var res = await _userService.DeleteUserByIdAsync(id);
            if (res) { return ResultHelper.Success("删除成功"); }
            return ResultHelper.Error("删除失败");
        }
        [HttpPut]
        public async Task<ApiResult> UpdateUser(UserReq userReq)
        {
            _logger.LogInformation("请求参数为：userReq:{}", userReq.ToString());
            var res = await _userService.UpdateUserByIdAsync(userReq);
            if (res) { return ResultHelper.Success("修改成功"); }
            return ResultHelper.Error("修改失败");
        }
        [HttpGet("{id}")]
        public async Task<ApiResult> GetUserById(int id)
        {
            _logger.LogInformation("请求参数为：id:{}", id);
            var res = await _userService.GetUserByIdAsync(id);
            return ResultHelper.Success(res);
        }
    }
}
